import 'dart:async';
import 'package:BeeApp/CarPage/MainCarUserPage.dart';
import 'package:BeeApp/LoginAndRegister/ChooseUserPage.dart';
import 'package:BeeApp/LoginAndRegister/LoginModelPage.dart';
import 'package:BeeApp/LoginAndRegister/RegisterPage.dart';
import 'package:BeeApp/LoginAndRegister/ChangePWPage.dart';
import 'package:BeeApp/ShopPage/MainShopUserPage.dart';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:flutter/material.dart';
import 'package:BeeApp/MainPage/http_request.dart';
import 'package:BeeApp/MainPage/MainToolPage.dart';
import 'package:permission_handler/permission_handler.dart';

class LoginPage extends StatefulWidget {
  LoginPage({Key key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  String yzmText = "发送验证码";
  Timer countDownTimer;
  DateTime lastPopTime;
  LoginModel model;

  // 1 验证码登录  2 密码登录
  int loginType = 1;
  final mobileText01 = TextEditingController();
  final mobileText02 = TextEditingController();
  final codeText = TextEditingController();
  final passwordText = TextEditingController();
  @override
  void initState() {
    super.initState();
    // setWXPay();
    getAddress();
  }

  void getAddress() async {
    PermissionStatus permissions = await Permission.locationWhenInUse.request();
    if (permissions.isGranted) {
      Location location = await AmapLocation.instance.fetchLocation();
      setData("city", location.city);
      setData("lat", location.latLng.latitude);
      setData("long", location.latLng.longitude);
      print("地址全程${location.address}");
      print("经纬度${location.latLng}");
      print("省份${location.province}");
      print("城市${location.city}");
      print("区域${location.district}");
      print("poi名称${location.poiName}");
      print("街道${location.street}");
      print("街道号${location.streetNumber}");
      print("aoi名称${location.aoiName}");
    } else {
      showToast('需要定位权限!');
    }
  }

  @override
  void dispose() {
    super.dispose();
    countDownTimer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text(loginType == 1 ? "手机验证码登录" : "账号密码登录"),
        centerTitle: true,
        elevation: 0,
        leading: IconButton(
          icon: Image.asset(
            "images/MainBackImage.png",
            height: 20,
            width: 20,
            color: Colors.black,
          ),
          // onPressed: () => Navigator.of(context).pop(),
          onPressed: () {
            Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(builder: (context) => ChooseUserPage()),
                (route) => false);
          },
        ),
        actions: [
          InkWell(
            child: Container(
              height: setHeight(88),
              width: setWidth(100),
              alignment: Alignment.center,
              child: Text(
                "注册",
                style: TextStyle(
                    color: Color(0xFF999999), fontSize: setFontSize(28)),
              ),
            ),
            onTap: () {
              print("object");
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => RegisterPage()));
            },
          )
        ],
      ),
      body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            FocusScope.of(context).requestFocus(FocusNode());
          },
          child: mainView()),
    );
  }

  Widget mainView() {
    return ListView(
      children: [
        Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              padding: EdgeInsets.all(20),
              child: Column(
                children: [
                  this.loginType == 1 ? mobileView01() : mobileView02(),
                  lineView(),
                  SizedBox(height: setHeight(10)),
                  this.loginType == 1 ? codeView() : passwordView(),
                  lineView(),
                  SizedBox(height: setHeight(60)),
                  loginView(),
                  SizedBox(height: setHeight(40)),
                  this.loginType == 1 ? changeBtnView01() : changeBtnView02(),
                ],
              ),
            ),
          ],
        ),
      ],
    );
  }

  Widget lineView() {
    return Container(
      height: 1,
      color: Color(0xFFEDEDED),
    );
  }

  Text textview01(String text) {
    return Text(
      text,
      style: TextStyle(
        color: Color(0xFF333333),
        fontSize: setFontSize(28),
      ),
    );
  }

  Text textview02(String text) {
    return Text(
      text,
      style: TextStyle(
        color: Color(0xFF999999),
        fontSize: setFontSize(28),
      ),
    );
  }

  TextStyle hintStyle() {
    return TextStyle(
      fontSize: setFontSize(32),
      color: Color(0xFFCBCBCB),
    );
  }

  TextStyle textStyle() {
    return TextStyle(
      fontSize: setFontSize(32),
      color: Color(0xFF333333),
    );
  }

  Widget mobileView01() {
    return Container(
      child: Row(
        children: [
          textview01("手机号:"),
          SizedBox(width: 10),
          Expanded(
              child: TextField(
            controller: mobileText01,
            textAlign: TextAlign.start,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "请输入手机号",
                hintStyle: hintStyle()),
            style: textStyle(),
          )),
          Container(
            child: OutlineButton(
              onPressed: yzmText == "发送验证码" ? getCode : null,
              padding: EdgeInsets.only(left: 8, right: 8),
              borderSide: BorderSide(color: maincolor),
              highlightedBorderColor: maincolor,
              child: Text(yzmText),
              textColor: maincolor,
            ),
          ),
          SizedBox(width: setWidth(4)),
        ],
      ),
    );
  }

  void getCode() {
    DioUtils.postHttp(
      context,
      "user/send_code",
      parameters: {
        "user_type": getData("AppType"),
        "mobile": mobileText01.text,
        "event": "mobilelogin",
      },
      onSuccess: (t) {
        if (t["code"].toString() == "1") {
          // ignore: unnecessary_statements
          yzmText == "发送验证码" ? codeGet() : null;
        }
        showToast(t["msg"]);
      },
      onError: (error) {
        print("$error");
      },
    );
  }

  void codeGet() {
    countDownTimer?.cancel(); //如果已存在先取消置空
    countDownTimer = null;
    countDownTimer = Timer.periodic(Duration(seconds: 1), (t) {
      if (mounted) {
        setState(() {
          if (60 - t.tick > 0) {
            //60-t.tick代表剩余秒数，如果大于0，设置yzmText为剩余秒数，否则重置yzmText，关闭countTimer
            // yzmText = "(${60 - t.tick}s)后请重试";
            yzmText = "${60 - t.tick}秒";
          } else {
            yzmText = '发送验证码';
            countDownTimer.cancel();
            countDownTimer = null;
          }
        });
      }
    });
  }

  Widget codeView() {
    return Container(
      color: Colors.white,
      // padding: EdgeInsets.only(left: 20, right: 20),
      child: Row(
        children: [
          textview01("验证码:"),
          SizedBox(width: 10),
          Expanded(
              child: TextField(
            controller: codeText,
            textAlign: TextAlign.start,
            keyboardType: TextInputType.number,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "请输入短信验证码",
                hintStyle: hintStyle()),
            style: textStyle(),
          )),
        ],
      ),
    );
  }

  Widget mobileView02() {
    return Container(
      color: Colors.white,
      // padding: EdgeInsets.only(left: 20, right: 20),
      child: Row(
        children: [
          textview01("账号:"),
          SizedBox(width: 10),
          Expanded(
              child: TextField(
            controller: mobileText02,
            textAlign: TextAlign.start,
            cursorColor: Colors.grey[400], //设置光标
            decoration: InputDecoration(
                border: InputBorder.none,
                hintText: "请输入手机号",
                hintStyle: hintStyle()),
            style: textStyle(),
          )),
        ],
      ),
    );
  }

  Widget passwordView() {
    return Container(
      color: Colors.white,
      // padding: EdgeInsets.only(left: 20, right: 20),
      child: Row(
        children: [
          textview01("密码:"),
          SizedBox(width: 10),
          Expanded(
            child: TextField(
              obscureText: true,
              controller: passwordText,
              textAlign: TextAlign.start,
              cursorColor: Colors.grey[400], //设置光标
              decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: "请输入密码",
                  hintStyle: hintStyle()),
              style: textStyle(),
            ),
          ),
        ],
      ),
    );
  }

  Widget loginView() {
    return InkWell(
      child: Container(
        alignment: Alignment.center,
        width: 900,
        height: setHeight(100),
        decoration: BoxDecoration(
          color: maincolor,
          borderRadius: BorderRadius.all(
            Radius.circular(setHeight(10)),
          ),
        ),
        child: Text(
          "登录",
          style: TextStyle(color: Colors.white, fontSize: setFontSize(34)),
        ),
      ),
      onTap: () {
        if (this.loginType == 1) {
          codeLogin();
        } else {
          passwordLogin();
        }
      },
    );
  }

  void codeLogin() {
    if (!isPhone(mobileText01.text)) {
      showToast("请输入正确的手机号");
      return;
    }
    if (codeText.text.length == 0) {
      showToast("请输入验证");
      return;
    }
    showLoading(context);
    DioUtils.postHttp(
      context,
      "user/mobilelogin",
      parameters: {
        "user_type": getData("AppType").toString(),
        "mobile": mobileText01.text,
        "code": codeText.text,
      },
      onSuccess: (t) {
        dismissLoading(context);
        model = LoginModel.fromJson(t);
        if (model.code == 1) {
          setData("id", model.data.userinfo.id);
          setData("token", model.data.userinfo.token);
          setData("user_type", model.data.userinfo.userType);
          setData("avatar", model.data.userinfo.avatar);
          setData("nickname", model.data.userinfo.nickname);
          setData("mobile", model.data.userinfo.mobile);
          setData("sex", model.data.userinfo.sex);
          // 1 货主 2 车主
          if (getData("AppType") == "1") {
            setData("loginType", "1");
            Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(builder: (context) => MainShopUserPage()),
                (route) => false);
          } else {
            setData("loginType", "1");
            Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(builder: (context) => MainCarUserPage()),
                (route) => false);
          }
        } else {
          showToast(t["msg"]);
        }
      },
      onError: (error) {
        dismissLoading(context);
        print("$error");
      },
    );
  }

  void passwordLogin() {
    if (!isPhone(mobileText02.text)) {
      showToast("请输入正确的手机号");
      return;
    }
    if (passwordText.text.length == 0) {
      showToast("请输入密码");
      return;
    }
    showLoading(context);
    DioUtils.postHttp(
      context,
      "user/login",
      parameters: {
        "user_type": getData("AppType").toString(),
        'username': mobileText02.text,
        'password': passwordText.text
      },
      onSuccess: (t) {
        dismissLoading(context);
        model = LoginModel.fromJson(t);
        if (model.code == 1) {
          setData("id", model.data.userinfo.id);
          setData("token", model.data.userinfo.token);
          setData("user_type", model.data.userinfo.userType);
          setData("avatar", model.data.userinfo.avatar);
          setData("nickname", model.data.userinfo.nickname);
          setData("mobile", model.data.userinfo.mobile);
          setData("sex", model.data.userinfo.sex);

          // 1 货主 2 车主
          if (getData("AppType") == "1") {
            setData("loginType", "1");
            Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(builder: (context) => MainShopUserPage()),
                (route) => false);
          } else {
            setData("loginType", "1");

            Navigator.pushAndRemoveUntil(
                context,
                MaterialPageRoute(builder: (context) => MainCarUserPage()),
                (route) => false);
          }
        } else {
          showToast(t["msg"]);
        }
      },
      onError: (error) {
        dismissLoading(context);
        print("$error");
      },
    );
  }

  Widget changeBtnView01() {
    return Container(
      child: InkWell(
        child: textview02("帐号密码登录"),
        onTap: () {
          print("object");
          setState(() {
            this.loginType = 2;
            yzmText = '发送验证码';
            countDownTimer?.cancel();
            // countDownTimer? = null;
          });
        },
      ),
    );
  }

  Widget changeBtnView02() {
    return Container(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          InkWell(
            child: textview02("手机验证码登录"),
            onTap: () {
              print("object");
              setState(() {
                this.loginType = 1;
              });
            },
          ),
          Text(
            "|",
            style:
                TextStyle(color: Color(0xFF999999), fontSize: setFontSize(30)),
          ),
          InkWell(
            child: textview02("忘记密码     "),
            onTap: () {
              print("object");
              Navigator.push(context,
                  MaterialPageRoute(builder: (context) => ChangePWPage()));
            },
          ),
        ],
      ),
    );
  }

  Widget bottonView() {
    return Column(
      children: [
        Row(mainAxisAlignment: MainAxisAlignment.center, children: [
          Text(
            "        ",
            style: TextStyle(
                decoration: TextDecoration.lineThrough,
                decorationColor: Color(0xFF999999)),
          ),
          Text(
            "其他登录方式",
            style:
                TextStyle(color: Color(0xFF999999), fontSize: setFontSize(24)),
          ),
          Text(
            "        ",
            style: TextStyle(
                decoration: TextDecoration.lineThrough,
                decorationColor: Color(0xFF999999)),
          )
        ]),
        IconButton(
            icon: Image.asset(
              "images/MainWeiXinImage.png",
              height: setHeight(100),
              width: setHeight(100),
            ),
            onPressed: () {
              print("object");
              // loginWX();
            })
      ],
    );
  }
}
